import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:orginone/dart/extension/index.dart';
import 'package:orginone/components/ProcessDetailsWidget/components/BottomActionWidget.dart';
import 'package:orginone/components/form/form_widget/view.dart';
import 'package:orginone/components/form/mapping_components.dart';
import 'package:orginone/config/theme/space.dart';
import 'package:orginone/main.dart';
import 'package:orginone/dart/base/model.dart';
import 'package:orginone/dart/base/schema.dart';
import 'package:orginone/dart/core/work/task.dart';
import 'package:orginone/utils/log/log_util.dart';
import '../../../../dart/core/public/consts.dart';
import '../../../XTextField/XTextField.dart';
import '../../../form/form_widget/form_tool.dart';
import '../WorkTool.dart';
import 'components/XDocument.dart';
import 'components/XTabBar.dart';

///基本信息 页面
class ProcessInfoWidget extends StatefulWidget {
  IWorkTask? todo;
  ProcessInfoWidget({super.key, required this.todo});

  @override
  State<ProcessInfoWidget> createState() => _ProcessInfoPageState();
}

class _ProcessInfoPageState extends State<ProcessInfoWidget> {
  TextEditingController comment = TextEditingController();
  // IWorkTask? todo;

  WorkNodeModel? node;

  var xAttribute = {};

  List<XForm> mainForm = [];

  List<XForm> subForm = [];

  // late TabController subTabController;

  // late TabController mainTabController;

  // late TabController tabController;

  var mainIndex = 0;

  var subIndex = 0;

  List<String> tabTitle = [
    '办事详情',
    '历史痕迹',
  ];

  Future<void> loadDataInfo() async {
    node = WorkTool.getNodeByNodeId(widget.todo?.instanceData?.node?.id ?? "",
        node: widget.todo?.instanceData?.node);
    if (node != null) {
      mainForm = node!.primaryForms ?? [];

      // mainForm.value = node!.forms
      //         ?.where((element) => element.typeName == "主表")
      //         .toList() ??
      //     [];
      // mainTabController = TabController(length: mainForm.length, vsync: this);
      for (var element in mainForm) {
        element.data = getFormData(element.id);
        element.fields = widget.todo?.instanceData?.fields?[element.id] ?? [];
        for (var field in element.fields) {
          field.field = await FormTool.initFields(field);
        }
      }
      subForm = node!.detailForms ?? [];
      // subForm.value = node!.forms
      //         ?.where((element) => element.typeName == "子表")
      //         .toList() ??
      //     [];
      // subTabController = TabController(length: subForm.length, vsync: this);
      for (var element in subForm) {
        element.data = getFormData(element.id);
        element.fields = widget.todo?.instanceData?.fields?[element.id] ?? [];
        for (var field in element.fields) {
          field.field = await FormTool.initFields(field);
        }
      }

      // mainForm.refresh();
      // subForm.refresh();
      // setState(() {
      // });
    }
  }

  FormEditData getFormData(String id) {
    final source = <AnyThingModel>[];
    if (widget.todo?.instanceData?.data != null &&
        widget.todo?.instanceData?.data![id] != null) {
      final beforeData = widget.todo?.instanceData!.data![id]!;
      if (beforeData != null) {
        final nodeData = beforeData.where((i) => i.nodeId == node?.id).toList();
        if (nodeData.isNotEmpty) {
          return nodeData.last;
        }
      }
    }
    var data = FormEditData(
      nodeId: node?.id,
      // creator: belong.userId,
      createTime: DateTime.now().toDateString(format: 'yyyy-MM-dd hh:mm:ss.S'),
      before: [], after: [],
    );
    data.before = List.from(source);
    data.after = List.from(source);
    return data;
  }

  @override
  Widget build(BuildContext context) {
    // tabController = TabController(length: tabTitle.length, vsync: this);
    // Future.delayed(const Duration(seconds: 0), () async {
    // await loadDataInfo();
    // });
    return FutureBuilder(
      builder: (context, sho) {
        if (sho.connectionState == ConnectionState.done) {
          return _mainView();
        }
        return const Center(
          child: CircularProgressIndicator(),
        );
      },
      future: loadDataInfo(),
    );
  }

  Column _mainView() {
    return Column(
      children: [
        Expanded(
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                FormWidget(
                  mainForm: mainForm ?? [],
                  subForm: subForm ?? [],
                ),
                // _mainTable(),
                // _subTable(),
                // SizedBox(
                //   height: 10.h,
                // ),
                _opinion()
              ],
            ),
          ),
        ),
        (widget.todo?.metadata.status != 1 || widget.todo?.taskdata.approveType == "抄送") ? Container() : BottomActionWidget(
          todo: widget.todo,
          comment: comment,
        ),
      ],
    );
  }

  Widget _opinion() {
    if (widget.todo?.metadata.status != 1 || widget.todo?.taskdata.approveType == "抄送") {
      return Container();
    }
    return XTextField.input(
      title: "备注",
      required: true,
      // backgroundColor: XColors.cardBackgroundColor,
      hint: "请填写备注信息",
      // hint: "请输入审批意见",
      controller: comment,
      maxLines: 4,
    ).paddingVertical(AppSpace.listItem).paddingHorizontal(AppSpace.page);
  }
  // Column _mainViewOld() {
  //   return Column(
  //     children: [
  //       Expanded(
  //         child: SingleChildScrollView(
  //           child: Column(
  //             crossAxisAlignment: CrossAxisAlignment.start,
  //             children: [
  //               const FormWidget(),
  //               _mainTable(),
  //               _subTable(),
  //               SizedBox(
  //                 height: 10.h,
  //               ),
  //               ApproveWidget(todo: todo),
  //             ],
  //           ),
  //         ),
  //       ),
  //     ],
  //   );
  // }

  Widget _mainTable() {
    if (mainForm.isEmpty) {
      return const SizedBox();
    }
    XLogUtil.d('AAAAAAAAAAA${jsonEncode(mainForm)}');
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        XTabBar(null, mainForm.map((element) => element.name).toList(),
            onTap: (index) {
          changeMainIndex(index);
        }, labelStyle: TextStyle(fontSize: 21.sp)),
        _buildMainFormView(),
      ],
    );
  }

  _buildMainFormView() {
    List<Widget> fileds = mainForm[mainIndex].fields.map((element) {
      XLogUtil.dd('_buildMainFormView-element');
      XLogUtil.dd(element.toJson());
      Map<String, dynamic> info = {};
      if (mainForm[mainIndex].data?.after.isNotEmpty ?? false) {
        info = mainForm[mainIndex].data!.after[0].otherInfo;
      }
      return FutureBuilder(
        builder: (context, snapshot) {
          if (snapshot.connectionState != ConnectionState.done &&
              !snapshot.hasData) {
            return Container();
          }
          Widget child = null != relationCtrl.user
              ? mappingComponents[element.field.type ?? ""]!(
                  element.field, relationCtrl.user!)
              : Container();
          return child;
        },
        future: loadMainFieldData(element, info),
      );
    }).toList();

    return Column(
      children: fileds,
    );
  }

  Widget _subTable() {
    if (subForm.isEmpty) {
      return const SizedBox();
    }
    return Container(
      margin: EdgeInsets.only(top: 10.h),
      child: Column(
        children: [
          XTabBar(null, subForm.map((element) => element.name ?? '').toList(),
              onTap: (index) {
            changeSubIndex(index);
          }, labelStyle: TextStyle(fontSize: 21.sp)),
          _buildSubFormView(),
        ],
      ),
    );
  }

  _buildSubFormView() {
    var sub = subForm[subIndex];
    List<String> title = sub.fields.map((e) => e.name ?? "").toList() ?? [];
    return FutureBuilder<List<List<String>>>(
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return XDocument(
            title: ["唯一标识", "创建者", "状态", ...title],
            content: snapshot.data ?? [],
          );
        }
        return Container();
      },
      future: loadSubFieldData(sub, sub.fields),
    );
  }

  Future<bool> loadMainFieldData(
      FieldModel field, Map<String, dynamic> data) async {
    var value = data[field.id];
    if (value == null) {
      return false;
    }
    await _buildField(field, value);
    return true;
  }

  Future<String> _buildField(FieldModel field, dynamic value) async {
    if (field.field.type == "input") {
      field.field.controller!.text = (value ?? "").toString();
      return value.toString() ?? "";
    } else {
      switch (field.field.type) {
        case "selectPerson":
        case "selectDepartment":
        case "selectGroup":
          field.field.defaultData.value =
              relationCtrl.user?.findShareById(value);
          return field.field.defaultData.value.name;
        case "select":
        case 'switch':
          field.field.select = {};
          for (var value in field.lookups ?? []) {
            field.field.select![value.value] = value.text ?? "";
          }
          if (field.field.type == "select") {
            field.field.defaultData.value = {value: field.field.select![value]};
          } else {
            field.field.defaultData.value = value ?? "";
          }
          return field.field.select![value] ?? "";
        case "upload":
          field.field.defaultData.value =
              value != null ? FileItemModel.fromJson(value) : null;
          return field.field.defaultData.value.name;
        default:
          field.field.defaultData.value = value;
          if (field.field.type == "selectTimeRange" ||
              field.field.type == "selectDateRange") {
            return field.field.defaultData.value.join("至");
          }
          return value ?? "";
      }
    }
  }

  Future<List<List<String>>> loadSubFieldData(
      XForm form, List<FieldModel> fields) async {
    List<List<String>> content = [];
    for (var thing in form.data!.after) {
      List<String> data = [
        thing.id ?? thing.otherInfo['id'] ?? '',
        thing.status.toString() ?? "",
        ShareIdSet[thing.creater]?.name ?? "",
      ];
      for (var field in fields) {
        dynamic value = thing.otherInfo[field.id];
        if (value == null) {
          data.add('');
        } else {
          try {
            if (field.name!.contains("是否启用")) {
              XLogUtil.d('');
            }
            data.add(await _buildField(field, thing.otherInfo[field.id]));
          } catch (e) {
            XLogUtil.d('');
          }
        }
      }
      content.add(data);
    }
    return content;
  }

  void changeMainIndex(int index) {
    if (mainIndex != index) mainIndex = index;
  }

  void changeSubIndex(int index) {
    if (subIndex != index) subIndex = index;
  }
}
